package com.jf3q.sup.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.sup.domain.Departments;
import com.jf3q.sup.service.DepartmentsService;
import com.jf3q.sup.utils.Constant;
import com.jf3q.sup.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("departments")
public class DepartmentsController {

    @Autowired
    private DepartmentsService departmentsService;

    /**
     * 分页查询
     */
    @PreAuthorize("hasAnyAuthority('/departments')")
    @GetMapping("")
    public ResultVo getPage(String name, @RequestParam(defaultValue = "1") Integer pageNum){
        IPage<Departments> page = Page.of(pageNum, Constant.PAGE_SIZE);
        page=departmentsService.page(page,
                new LambdaQueryWrapper<Departments>().like(StringUtils.isNotEmpty(name),Departments::getName,name));
        return ResultVo.success(null,page);
    }

    /**
     * 新增查询
     */
    @PreAuthorize("hasAnyAuthority('/departments/add')")
    @PostMapping("")
    public ResultVo save(@RequestBody Departments departments){
        try {
            departmentsService.save(departments);
        } catch (Exception e) {
            throw new RuntimeException("新增部门出问题啦!"+e.getMessage());
        }
        return ResultVo.success("新增部门成功",null);
    }

    @PreAuthorize("hasAnyAuthority('/departments/edit')")
    @PutMapping("")
    public ResultVo edit(@RequestBody Departments departments){
        try {
            departmentsService.updateById(departments);
        } catch (Exception e) {
            throw new RuntimeException("修改部门出问题啦!"+e.getMessage());
        }
        return ResultVo.success("修改部门成功",null);
    }


    @PreAuthorize("hasAnyAuthority('/departments/delete')")
    @DeleteMapping("{id}")
    public ResultVo del(@PathVariable Integer id){
        try {
            departmentsService.removeById(id);
        } catch (Exception e) {
            throw new RuntimeException("刪除部门出问题啦!"+e.getMessage());
        }
        return ResultVo.success("刪除部门成功",null);
    }
}
